# from service.data import DataProcess
from service.common import find_data, insert_data
from service.handle_format import request_handle_proxy
from pao_python.pao.data import process_db, get_date, dataframe_to_list, DataProcess
import uuid
import pandas as pd


class AnalysisSign(DataProcess):

    def cal_analysis_sign(self, handle_code):
        res = {}

        def process_func(db):
            nonlocal res
            find_result = find_data(db, 'IDMIS_Handle', {
                                    'handle_code': handle_code})
            if len(find_result) > 0:
                if find_result[0]['handle_type'] != 'external_links':
                    arttribute = request_handle_proxy(handle_code)
                    # 数据去重
                    pd_attribute = pd.DataFrame(
                        arttribute).drop_duplicates(['index'])
                    get_arttribute = dataframe_to_list(pd_attribute)
                    # 判断是否存在排序字段module_sort
                    module_sort = {}
                    print('find_result', find_result)
                    if 'module_sort' in find_result[0].keys():
                        module_sort = find_result[0]['module_sort']
                    if (len(get_arttribute) > 0):
                        res = {
                            'handle_code': handle_code,
                            'handle_name': find_result[0]['handle_name'],
                            'attribute': get_arttribute,
                            'module_sort': module_sort
                        }
                else:
                    pd_result = pd.DataFrame(find_result).drop(['_id'], axis=1)
                    res = dataframe_to_list(pd_result)[0]

                # 增加解析记录
                new_analysis_record = {
                    'id': str(uuid.uuid1()),
                    'handle_id': find_result[0]['id'],
                    'handle_type': find_result[0]['handle_type'],
                    'handle_code': find_result[0]['handle_code'],
                    'date': get_date()
                }
                insert_data(db, 'IDMIS_Analysis_Record', new_analysis_record)

            else:
                res = False
        process_db(self.db_addr, self.db_port, self.db_name, process_func)
        return res
